﻿using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CCOA.Main
{
    /// <summary>
    /// 主面板模块
    /// </summary>
    public partial class Default : System.Web.UI.Page
    {
        #region //接口部分
        public bool IsAdmin
        {
            get { return BP.Web.WebUser.No.ToLower() == "admin"; }
        }
        /// <summary>
        /// GPM首页地址
        /// </summary>
        public string GPM_HomePage
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["CCPortal.HomePage"];
            }
        }
        /// <summary>
        /// GPM组织管理地址
        /// </summary>
        public string GPM_GPMPage
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["CCPortal.GPMPage"] + "&UserNo=" + BP.Web.WebUser.No + "&SID=" + BP.Web.WebUser.SID;
            }
        }
        /// <summary>
        /// GPM组织管理地址
        /// </summary>
        public string BPM_BPMPage
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["CCPortal.BPMPage"] + "&UserNo=" + BP.Web.WebUser.No + "&SID=" + BP.Web.WebUser.SID;
            }
        }
        /// <summary>
        /// 系统在菜单中的编号
        /// </summary>
        public string AppMenuNo
        {
            get
            {
                string appMenuNo = BP.Sys.SystemConfig.AppSettings["AppMenuNo"];
                if (string.IsNullOrEmpty(appMenuNo))
                    return "2002";
                return appMenuNo;
            }
        }
        /// <summary>
        /// 系统菜单显示方式
        /// </summary>
        public string AppMenuModel
        {
            get
            {
                string appMenuModel = BP.Sys.SystemConfig.AppSettings["AppMenuModel"];
                if (string.IsNullOrEmpty(appMenuModel))
                    return "0";
                return appMenuModel;
            }
        }
        
        /// <summary>
        /// 用户标题接口
        /// </summary>
        public string UserTitle
        {
            get
            {
                return BP.Web.WebUser.No;
            }
        }
        /// <summary>
        /// 用户菜单接口，用户菜单自定义，必须按格式输出。
        /// </summary>
        public string MenuList
        {
            get
            {
                //测试用
                //return BP.DA.DataType.ReadTextFile(Server.MapPath("doc/DefaultMenu.txt"));

                //使用GPM后删除上面一句
                string userName = BP.Web.WebUser.No;
                DataTable dtMenu = BP.OA.GPM.GetUserMenuOfDatatable(userName);
                //转化成可用的DataTable，此数据从GPM来
                if (dtMenu != null)
                {
                    dtMenu.Columns["FK_Menu"].ColumnName = "menuid";
                    dtMenu.Columns["Name"].ColumnName = "menuname";
                    dtMenu.Columns["ParentNo"].ColumnName = "parentid";
                    dtMenu.Columns["Url"].ColumnName = "url";
                    dtMenu.Columns["WebPath"].ColumnName = "icon";
                    dtMenu.Columns["MenuType"].ColumnName = "degree";
                }
                foreach (DataRow dr in dtMenu.Rows)
                {
                    string icon = String.Format("{0}", dr["icon"]);
                    //修改菜单左侧显示路径 hzm
                    if (!String.IsNullOrEmpty(icon) && icon.StartsWith("//")) icon = icon.Substring(1);
                    icon = String.Format("{0}{1}", this.GPM_HomePage, icon);
                    dr["icon"] = string.IsNullOrEmpty(icon) ? BP.WF.Glo.CCFlowAppPath + "WF/Img/FileType/ie.gif" : icon;
                }
                //进入面板，得转化成面板的规则
                return new BuildUserMenus(dtMenu).GetUserMenu(AppMenuNo);
            }
        }
        /// <summary>
        /// 用户首页接口，每个用户首页可以定制
        /// </summary>
        public string DesktopUrl
        {
            get
            {
                string deskTop = BP.OA.Main.GetConfigItem("DeskTopUrl");
                deskTop = string.IsNullOrEmpty(deskTop) ? "Desktop.aspx" : deskTop;
                return deskTop;
            }
        }
        private void LoginOut()
        {
            BP.OA.Auth.LoginOut();
            Response.Redirect(BP.OA.Auth.Login_Url);
        }
        #endregion
        //*****************主面板部分**************************
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                //判断数据库是否安装

                if (BP.DA.DBAccess.IsExitsObject("OA_Article") == false)
                {
                    this.Response.Redirect(BP.OA.Auth.DBInstall_Url, true);
                    return;
                }

                //注销专用
                if (Request["logout"] != null && Request["logout"] == "1")
                {
                    this.LoginOut();
                    return;
                }

                //判断是否登录
                if (!BP.OA.Auth.IsOnline())
                {
                    this.Response.Redirect(BP.OA.Auth.Login_Url, true);
                    return;
                }
            }
        }
    }
    //***********以下为Json支持类**************************
    public class JsonConvert
    {
        public static T GetJsonObject<T>(string jsonString, bool objectIsSerialized)
        {
            if (objectIsSerialized)
            {
                using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonString)))
                { return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms); }
            }
            else
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                try
                {
                    return jss.Deserialize<T>(jsonString);
                }
                catch
                {
                    return default(T);
                }
            }
        }
        public static string GetJsonString(object jsonObject, bool objectIsSerialized)
        {
            if (objectIsSerialized)
            {
                using (var ms = new MemoryStream())
                {
                    new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
                    return System.Text.Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            else
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
            }
        }
    }
    //用于Json组织菜单单元
    //[DataContract]
    //public class UserMenu
    //{
    //    [DataMember(Order = 0)]
    //    public string menuid { get; set; }
    //    [DataMember(Order = 1)]
    //    public string menuname { get; set; }
    //    [DataMember(Order = 2)]
    //    public string icon { get; set; }
    //    [DataMember(Order = 3)]
    //    public string url { get; set; }
    //    [DataMember(Order = 4)]
    //    public List<UserMenu> menus { get; set; }
    //}
    public class UserMenu
    {
        public string menuid { get; set; }
        public string menuname { get; set; }
        public string icon { get; set; }
        public string url { get; set; }
        public List<UserMenu> menus { get; set; }
        public List<UserMenu> child { get; set; }
    }
    /// <summary>
    /// 生成用户Menu类
    /// 必须输入有menuid,menuname,parentid,url,icon,degree的DataTable，才能输出可用的菜单字符串。
    /// </summary>
    public class BuildUserMenus
    {
        private DataTable DTBase = null;
        /// <summary>
        /// 生成菜单类
        /// </summary>
        /// <param name="dtMenu">必须拥有字段：menuid,menuname,parentid,url,icon,degree</param>
        public BuildUserMenus(DataTable dtMenu)
        {
            this.DTBase = dtMenu;
        }
        public string GetUserMenu(string parentNo)
        {
            List<UserMenu> UserMenus = this.CreateMenuByParentId(parentNo);
            return JsonConvert.GetJsonString(UserMenus, false);
        }
        private List<UserMenu> CreateMenuByParentId(string id)
        {
            List<UserMenu> userMenus = new List<UserMenu>();
            DataRow[] drs = this.DTBase.Select("parentid='" + id + "'");
            foreach (DataRow dr in drs)
            {
                List<UserMenu> userMenus_childs = this.CreateMenuByParentId(Convert.ToString(dr["menuid"]));
                UserMenu umNew = new UserMenu()
                {
                    menuid = Convert.ToString(dr["menuid"])
                  ,
                    menuname = Convert.ToString(dr["menuname"])
                  ,
                    icon = Convert.ToString(dr["icon"])
                  ,
                    url = Convert.ToString(dr["url"])
                };
                if (userMenus_childs.Count > 0)
                {
                    switch (Convert.ToInt32(dr["degree"]))
                    {
                        case 3:
                            umNew.menus = userMenus_childs;
                            break;
                        case 4:
                            if (userMenus_childs != null && userMenus_childs.Count > 0)
                            {
                                if (string.IsNullOrEmpty(umNew.icon) || umNew.icon.Contains("WF/Img/FileType/ie.gif"))
                                {
                                    umNew.icon = BP.WF.Glo.CCFlowAppPath + "WF/Img/Tree/Dir.gif";
                                }
                            }
                            umNew.child = userMenus_childs;
                            break;
                    }

                }
                userMenus.Add(umNew);

            }
            return userMenus;
        }
    }
}
